import os
import pathlib
from .models import *
import base64


video_list_path = os.getenv('video_list')
root_items: list[DirItem] = []
# video_dict:dict[int,str]={}


def to_b64(source: str):
    buffer = source.encode('utf8')
    return base64.b64encode(buffer).decode('utf8')


def from_b64(source: str):
    print('Accept b64:',source)
    buffer = source.encode('utf8')
    return base64.b64decode(buffer).decode('utf8')


def get_video_repo_path():
    with open(video_list_path, encoding='utf8') as f:
        return [line.strip() for line in f]


# def create_dir_item(dir_path:str):
#     path=pathlib.Path(dir_path)
#     dir_item= DirItem(name=path.name,parent='')
#     for sub_path in path.glob('*'):
#         if sub_path.is_file() and sub_path.suffix.lower()=='.mp4':
#             video_item=VideoItem(name=sub_path.name,parent=dir_item.name)
#             # video_item=VideoItem(name=sub_path.name,path=str(sub_path))
#             dir_item.videos.append(video_item)
#         if sub_path.is_dir():
#             sub_dir_item=create_dir_item(sub_path)
#             sub_dir_item.parent=dir_item.name
#             dir_item.sub_dirs.append(sub_dir_item)
#     return dir_item

def create_dir_item(dir_path):
    path = pathlib.Path(dir_path)
    dir_name = path.name
    videos = []
    sub_dirs = []
    for child in path.glob("*"):
        if child.is_file() and child.suffix.lower() == '.mp4':
            videos.append(child.name)
        elif child.is_dir():
            sub_dirs.append(child.name)
    return DirItem(name=dir_name, path=to_b64(dir_path), sub_dirs=sub_dirs, videos=videos)


def get_root_dir_items(refresh=False):
    global root_items
    if not root_items or refresh:
        root_items.clear()
        for path in get_video_repo_path():
            root_items.append(create_dir_item(path))
    return root_items


def get_dir_item(pid: str, did: str):
    parent_path = from_b64(pid)
    dir_name = from_b64(did)
    dir_path = os.path.join(parent_path, dir_name)
    if os.path.exists(dir_path) == False:
        print('Dir not found:', dir_path)
        return DirItem.NoExist(to_b64(dir_path), dir_name)
    return create_dir_item(dir_path)


def get_video_path(pid: str, vid: str):
    parent_path = from_b64(pid)
    video_name = from_b64(vid)
    video_path = os.path.join(parent_path, video_name)
    if os.path.exists(video_path) == False:
        print('No such video:',video_path)
        return None
    return video_path
